import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams } from 'react-router-dom'
import './index.scss'

import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useEffect, useState } from 'react'
import { createArticleAPI, getArticleById, updateArticleAPI } from '@/apis/article'
import { uploadImageAPI } from '@/apis/img'
import { useChannel } from '@/hooks/useChannel'
import { useRef } from 'react'

const { Option } = Select

const Publish = () => {
  // 获取频道列表
  const { channelList } = useChannel()

  // 提交表单
  const onFinish = async (formValue) => {
    console.log(formValue)
    //校验封面类型imageType是否和实际的图片列表imageList数量是相等的
    if (imageList.length !== imageType) return message.warning('封面类型和图片数量不匹配')
    const { title, content, categoryId } = formValue
    // 1. 按照接口文档的格式处理收集到的表单数据
    const reqData = {
      userId: 1,
      title,
      content,
      //markdownContent封面图片
      markdownContent: imageList.map(item => {
          if (item.response) {
            return item.response.data.url
          } else {
            return item.url
          }
        }),
      categoryId
    }
    console.log(reqData)
    // 2. 调用接口提交
    // 处理调用不同的接口 新增 - 新增接口  编辑状态 - 更新接口  id
    if (articleId) {
      // 更新接口
      updateArticleAPI({ ...reqData, id: articleId })
    } else {
       // 新增接口
    try {
      const createRes = await createArticleAPI(reqData) // 获取返回值
      console.log('文章创建成功', createRes)
      message.success('文章创建成功')
    } catch (error) {
      console.error('文章创建失败', error)
      message.error('文章创建失败')
    }
    }
  }

  // 富文本编辑器配置
  const quillRef = useRef(null)

  const modules = {
    toolbar: {
      container: [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote'],
        [{ header: [1, 2, 3, false] }],
        [{ list: 'ordered' }, { list: 'bullet' }],
        [{ align: [] }],
        [{ code_block: 'code' }],
        ['link', 'image']
      ]
    }
  }

  const formats = [
    'bold', 'italic', 'underline', 'strike',
    'blockquote', 'header', 'list', 'bullet',
    'align', 'code_block', 'link', 'image'
  ]






  // 上传回调
  const [imageList, setImageList] = useState([])
  // const onChange = (value) => {
  //   console.log('正在上传中', value)
  //   setImageList(value.fileList)
  // }

  // 切换图片封面类型
  const [imageType, setImageType] = useState(0)
  const onTypeChange = (e) => {
    console.log('切换封面了', e.target.value)
    setImageType(e.target.value)
  }

  // 回填数据
  const [searchParams] = useSearchParams()
  const articleId = searchParams.get('id')
  // 编辑文章时，获取实例
  const [form] = Form.useForm()

useEffect(() => {
  async function getArticleDetail() {
    const res = await getArticleById(articleId);
    const data = res.data;

    // Step 1: 提取 markdownContent 中的 URL
    const markdownContent = data.markdownContent?.trim();
    let imageUrl = '';
    if (markdownContent && markdownContent.startsWith('[') && markdownContent.endsWith(']')) {
      imageUrl = markdownContent.slice(1, -1);
    }

    // Step 2: 构造 Upload 需要的格式
    const isValidImage = imageUrl && imageUrl.startsWith('http');
    const fileList = isValidImage ? [{
      uid: -1,
      name: 'image.png',
      url: imageUrl
    }] : [];

    // Step 3: 更新状态
    setImageList(fileList);
    const imageType = isValidImage ? 1 : 0;
    setImageType(imageType);

    // Step 4: 设置表单字段（模拟 cover.type）
    form.setFieldsValue({
      title: data.title,
      categoryId: data.categoryId,
      content: data.contentHtml,
      cover: {
        type: imageType
      }
    });

    console.log('最终赋值:', {
      title: data.title,
      categoryId: data.categoryId,
      content: data.contentHtml,
      cover: {
        type: imageType
      }
    });
  }

  if (articleId) {
    getArticleDetail();
  }
}, [articleId, form]);
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> },
            { title: `${articleId ? '编辑' : '发布'}文章` },
          ]}
          />
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 0 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label=" 文章类型"
            name="categoryId"
            rules={[{ required: true, message: '请选择文章类型' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {/* value属性用户选中之后会自动收集起来作为接口的提交字段 */}
              {channelList.map(item => <Option key={item.categoryId} value={item.categoryId}>{item.categoryName}</Option>)}
            </Select>
          </Form.Item>
          <Form.Item label="封面">
        <Form.Item name={['cover', 'type']} initialValue={0}>
            <Radio.Group onChange={onTypeChange}>
              <Radio value={1}>单图</Radio>
              {/* <Radio value={3}>三图</Radio> */}
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
            {/* 
              listType: 决定选择文件框的外观样式
              showUploadList: 控制显示上传列表
            */}
            {imageType > 0 && <Upload
              listType="picture-card"
              showUploadList
              fileList={imageList}
              onChange={({ fileList }) => setImageList(fileList)}
              customRequest={async ({ file, onSuccess, onError }) => {
                const formData = new FormData()
                formData.append('myFileName', file)
                // 上传图片到服务器
                try {
                  const res = await uploadImageAPI(formData)
                  // 上传成功
                  file.url = res.data.url
                  onSuccess(res, file)
                } catch (error) {
                  onError(error)
                  message.error('封面图上传失败')
                }
              }}
            >
              <div style={{ marginTop: 8 }}>
                <PlusOutlined />
              </div>
            </Upload>}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            {/* 富文本编辑器 */}
             <ReactQuill
              className="publish-quill"
              ref={quillRef}
              theme="snow"
              placeholder="请输入文章内容"
              modules={modules}
              formats={formats}
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                发布文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish